import TJavaLib.TList;
import TJavaLib.TString;

import java.util.Random;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.BufferedReader;

public class twsnsim {
	public static long DF_TIME_TICK = 1;
	public static long DF_REFRESH_RATE = 0;

	public static TSimulator simulator;
	public static TNetwork network;
	
	public static Random random;

  public static TNetwork loadScenario(String sce) throws IOException {
  	TNetwork network = simulator.newNetwork();
  	BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(sce)));
		String line = null;
		TString st = new TString(';');
		
		//Dep. Area
		st.setStr(reader.readLine());
		int depW = (int)(Double.parseDouble(st.getStrAt(1)));
		int depH = (int)(Double.parseDouble(st.getStrAt(2)));
		network.setDepW(depW);
		network.setDepH(depH);
		
		//Number of nodes
		st.setStr(reader.readLine());
		int nnode = Integer.valueOf(st.getStrAt(1));
		
		//Comm & Sen ranges
		st.setStr(reader.readLine());
		TRadio.DF_RTX = Double.valueOf(st.getStrAt(1));
		st.setStr(reader.readLine());
		TSenInf.DF_RSEN = Double.valueOf(st.getStrAt(1));
		
		//Sensors
		for (int i=0; i<nnode; i++) {
			st.setStr(reader.readLine());
			if ((st.getStrAt(0)).equalsIgnoreCase("sensor")) {
				double x = Double.valueOf(st.getStrAt(1));
				double y = Double.valueOf(st.getStrAt(2));
				TSensor s = network.newSensor();
				s.setLoc(x, y);
				if (st.len() == 4) {
					String des = st.getStrAt(3);
					if ("des".equalsIgnoreCase(des)) {
						s.setType(TSensor.DESTINATION);
					}
				}
			} else {
				double x = Double.valueOf(st.getStrAt(1));
				double y = Double.valueOf(st.getStrAt(2));
				TGateway gw = network.newGateway();
				gw.setLoc(x, y);
			}
		}
		
		reader.close();
		return network;
	}
	
	public static void drawResult() {
		TResultView resView = new TResultView(network, "Simulation result:");
		resView.showFrame();
	}
	
  public static void main(String args[]) throws IOException, InterruptedException {
  	//Network scenario
  	String scePath = args[0];
  
		//Initialize simulator
		simulator = new TSimulator();
		simulator.setTimeTick(DF_TIME_TICK);
		
		//Simulation duration time
  	long simDuraTime = Long.valueOf(args[1]);
  	simulator.setDuraTime(simDuraTime*1000);

		//Load/create a network scenario
		network = loadScenario(scePath);
		
		//Run simulation
		simulator.start();
		while (!simulator.isStoped()) { Thread.sleep(1000);	}
		
		//Show simulation results
		drawResult();
		
		//Record statistic
	}	
}
